<template>
  <div class="grades-container">
    <div class="page-header">
      <h2>成绩管理</h2>
      <el-button v-if="userStore.isAdmin || userStore.isTeacher" type="primary" @click="handleAddGrade">
        <el-icon><Plus /></el-icon>录入成绩
      </el-button>
    </div>

    <el-card class="box-card">
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="学号">
            <el-input v-model="searchForm.studentId" placeholder="请输入学号" clearable />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="searchForm.studentName" placeholder="请输入姓名" clearable />
          </el-form-item>
          <el-form-item label="课程">
            <el-select v-model="searchForm.courseId" placeholder="请选择课程" clearable>
              <el-option
                v-for="item in courseList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="学期">
            <el-select v-model="searchForm.semester" placeholder="请选择学期" clearable>
              <el-option
                v-for="item in semesterList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="gradeList" style="width: 100%" border>
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="studentName" label="姓名" width="120" />
        <el-table-column prop="className" label="班级" width="150" />
        <el-table-column prop="courseName" label="课程" width="150" />
        <el-table-column prop="semester" label="学期" width="180" />
        <el-table-column prop="score" label="成绩" width="100">
          <template #default="scope">
            <el-tag :type="getScoreTagType(scope.row.score)">
              {{ scope.row.score }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="gradePoint" label="绩点" width="100" />
        <el-table-column prop="examDate" label="考试日期" width="120" />
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <template v-if="userStore.isAdmin || userStore.isTeacher">
              <el-button size="small" @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
            <span v-else>无操作权限</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 成绩统计 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>成绩分布</span>
            </div>
          </template>
          <div class="chart-container" ref="scoreDistributionChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>课程平均分</span>
            </div>
          </template>
          <div class="chart-container" ref="courseAverageChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加/编辑成绩对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '录入成绩' : '编辑成绩'"
      width="50%"
    >
      <el-form
        ref="gradeFormRef"
        :model="gradeForm"
        :rules="rules"
        label-width="100px"
        style="max-width: 600px"
      >
        <el-form-item label="学生" prop="studentId">
          <el-select
            v-model="gradeForm.studentId"
            filterable
            placeholder="请选择学生"
            @change="handleStudentChange"
          >
            <el-option
              v-for="item in studentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="gradeForm.courseId" filterable placeholder="请选择课程">
            <el-option
              v-for="item in courseList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学期" prop="semester">
          <el-select v-model="gradeForm.semester" placeholder="请选择学期">
            <el-option
              v-for="item in semesterList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成绩" prop="score">
          <el-input-number v-model="gradeForm.score" :min="0" :max="100" :precision="1" />
        </el-form-item>
        <el-form-item label="考试日期" prop="examDate">
          <el-date-picker
            v-model="gradeForm.examDate"
            type="date"
            placeholder="选择考试日期"
            format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="gradeForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useUserStore } from '../stores/user';
import * as echarts from 'echarts/core';
import { BarChart, PieChart } from 'echarts/charts';

// 初始化用户存储
const userStore = useUserStore();
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册 ECharts 组件
echarts.use([
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  CanvasRenderer,
]);

// 搜索表单
const searchForm = reactive({
  studentId: '',
  studentName: '',
  courseId: '',
  semester: '',
});

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 课程列表
const courseList = ref([
  { value: 'CS101', label: '计算机导论' },
  { value: 'CS102', label: '程序设计基础' },
  { value: 'CS201', label: '数据结构' },
  { value: 'CS301', label: '操作系统' },
  { value: 'CS302', label: '计算机网络' },
]);

// 学期列表
const semesterList = ref([
  { value: '2023-2024-1', label: '2023-2024学年第一学期' },
  { value: '2023-2024-2', label: '2023-2024学年第二学期' },
]);

// 学生选项
const studentOptions = ref([
  { value: '2023001', label: '2023001 - 张三' },
  { value: '2023002', label: '2023002 - 李四' },
  { value: '2023003', label: '2023003 - 王五' },
  { value: '2023004', label: '2023004 - 赵六' },
  { value: '2023005', label: '2023005 - 钱七' },
]);

// 学生信息映射
const studentMap = {
  '2023001': { name: '张三', className: '计算机科学与技术1班' },
  '2023002': { name: '李四', className: '计算机科学与技术1班' },
  '2023003': { name: '王五', className: '计算机科学与技术2班' },
  '2023004': { name: '赵六', className: '软件工程1班' },
  '2023005': { name: '钱七', className: '软件工程2班' },
};

// 课程信息映射
const courseMap = {
  CS101: '计算机导论',
  CS102: '程序设计基础',
  CS201: '数据结构',
  CS301: '操作系统',
  CS302: '计算机网络',
};

// 成绩列表
const gradeList = ref([
  {
    id: 1,
    studentId: '2023001',
    studentName: '张三',
    className: '计算机科学与技术1班',
    courseId: 'CS101',
    courseName: '计算机导论',
    semester: '2023-2024-1',
    score: 85,
    gradePoint: 3.7,
    examDate: '2023-12-20',
    remark: '',
  },
  {
    id: 2,
    studentId: '2023001',
    studentName: '张三',
    className: '计算机科学与技术1班',
    courseId: 'CS102',
    courseName: '程序设计基础',
    semester: '2023-2024-1',
    score: 92,
    gradePoint: 4.0,
    examDate: '2023-12-25',
    remark: '',
  },
  {
    id: 3,
    studentId: '2023002',
    studentName: '李四',
    className: '计算机科学与技术1班',
    courseId: 'CS101',
    courseName: '计算机导论',
    semester: '2023-2024-1',
    score: 78,
    gradePoint: 3.3,
    examDate: '2023-12-20',
    remark: '',
  },
  {
    id: 4,
    studentId: '2023002',
    studentName: '李四',
    className: '计算机科学与技术1班',
    courseId: 'CS102',
    courseName: '程序设计基础',
    semester: '2023-2024-1',
    score: 65,
    gradePoint: 2.0,
    examDate: '2023-12-25',
    remark: '期末考试缺勤，补考成绩',
  },
  {
    id: 5,
    studentId: '2023003',
    studentName: '王五',
    className: '计算机科学与技术2班',
    courseId: 'CS101',
    courseName: '计算机导论',
    semester: '2023-2024-1',
    score: 90,
    gradePoint: 4.0,
    examDate: '2023-12-20',
    remark: '',
  },
]);

// 图表引用
const scoreDistributionChart = ref<HTMLElement | null>(null);
const courseAverageChart = ref<HTMLElement | null>(null);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref<'add' | 'edit'>('add');
const gradeFormRef = ref<FormInstance>();
const gradeForm = reactive({
  id: 0,
  studentId: '',
  courseId: '',
  semester: '',
  score: 0,
  examDate: '',
  remark: '',
});

// 表单验证规则
const rules = reactive<FormRules>({
  studentId: [{ required: true, message: '请选择学生', trigger: 'change' }],
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  semester: [{ required: true, message: '请选择学期', trigger: 'change' }],
  score: [{ required: true, message: '请输入成绩', trigger: 'blur' }],
  examDate: [{ required: true, message: '请选择考试日期', trigger: 'change' }],
});

// 生命周期钩子
onMounted(() => {
  fetchGradeList();
  nextTick(() => {
    initCharts();
  });
});

// 获取成绩列表
const fetchGradeList = () => {
  // 模拟后端接口请求
  setTimeout(() => {
    // 这里应该是实际的API调用
    // 使用假数据
    total.value = gradeList.value.length;
  }, 300);
};

// 初始化图表
const initCharts = () => {
  // 成绩分布图表
  if (scoreDistributionChart.value) {
    const chart = echarts.init(scoreDistributionChart.value);
    const option = {
      title: {
        text: '成绩分布',
        left: 'center',
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)',
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: ['优秀', '良好', '中等', '及格', '不及格'],
      },
      series: [
        {
          name: '成绩分布',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 2, name: '优秀' },
            { value: 1, name: '良好' },
            { value: 1, name: '中等' },
            { value: 0, name: '及格' },
            { value: 1, name: '不及格' },
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    };
    chart.setOption(option);
    window.addEventListener('resize', () => {
      chart.resize();
    });
  }

  // 课程平均分图表
  if (courseAverageChart.value) {
    const chart = echarts.init(courseAverageChart.value);
    const option = {
      title: {
        text: '课程平均分',
        left: 'center',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: ['计算机导论', '程序设计基础', '数据结构', '操作系统', '计算机网络'],
        axisLabel: {
          interval: 0,
          rotate: 30,
        },
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
      },
      series: [
        {
          name: '平均分',
          type: 'bar',
          data: [84.3, 78.5, 0, 0, 0],
        },
      ],
    };
    chart.setOption(option);
    window.addEventListener('resize', () => {
      chart.resize();
    });
  }
};

// 获取成绩标签类型
const getScoreTagType = (score: number) => {
  if (score >= 90) return 'success';
  if (score >= 80) return 'info';
  if (score >= 70) return 'warning';
  if (score >= 60) return '';
  return 'danger';
};

// 计算绩点
const calculateGradePoint = (score: number) => {
  if (score >= 90) return 4.0;
  if (score >= 85) return 3.7;
  if (score >= 80) return 3.3;
  if (score >= 75) return 3.0;
  if (score >= 70) return 2.7;
  if (score >= 65) return 2.3;
  if (score >= 60) return 2.0;
  return 0;
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchGradeList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.studentId = '';
  searchForm.studentName = '';
  searchForm.courseId = '';
  searchForm.semester = '';
  currentPage.value = 1;
  fetchGradeList();
};

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchGradeList();
};

// 当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchGradeList();
};

// 学生选择变化
const handleStudentChange = (studentId: string) => {
  // 自动填充学生信息
  console.log('选择学生:', studentId);
};

// 添加成绩
const handleAddGrade = () => {
  dialogType.value = 'add';
  resetGradeForm();
  dialogVisible.value = true;
};

// 编辑成绩
const handleEdit = (row: any) => {
  dialogType.value = 'edit';
  Object.assign(gradeForm, {
    id: row.id,
    studentId: row.studentId,
    courseId: row.courseId,
    semester: row.semester,
    score: row.score,
    examDate: row.examDate,
    remark: row.remark,
  });
  dialogVisible.value = true;
};

// 删除成绩
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该成绩记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 模拟删除操作
      const index = gradeList.value.findIndex((item) => item.id === row.id);
      if (index !== -1) {
        gradeList.value.splice(index, 1);
        total.value -= 1;
        ElMessage.success('删除成功');
        // 重新初始化图表
        nextTick(() => {
          initCharts();
        });
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 重置表单
const resetGradeForm = () => {
  gradeForm.id = 0;
  gradeForm.studentId = '';
  gradeForm.courseId = '';
  gradeForm.semester = '';
  gradeForm.score = 0;
  gradeForm.examDate = '';
  gradeForm.remark = '';
};

// 提交表单
const submitForm = async () => {
  if (!gradeFormRef.value) return;

  await gradeFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 模拟添加操作
        const studentInfo = studentMap[gradeForm.studentId as keyof typeof studentMap];
        const newGrade = {
          id: Date.now(),
          studentId: gradeForm.studentId,
          studentName: studentInfo?.name || '',
          className: studentInfo?.className || '',
          courseId: gradeForm.courseId,
          courseName: courseMap[gradeForm.courseId as keyof typeof courseMap] || '',
          semester: gradeForm.semester,
          score: gradeForm.score,
          gradePoint: calculateGradePoint(gradeForm.score),
          examDate: gradeForm.examDate,
          remark: gradeForm.remark,
        };
        gradeList.value.push(newGrade);
        total.value += 1;
        ElMessage.success('添加成功');
      } else {
        // 模拟编辑操作
        const index = gradeList.value.findIndex((item) => item.id === gradeForm.id);
        if (index !== -1) {
          const studentInfo = studentMap[gradeForm.studentId as keyof typeof studentMap];
          const updatedGrade = {
            ...gradeList.value[index],
            studentId: gradeForm.studentId,
            studentName: studentInfo?.name || '',
            className: studentInfo?.className || '',
            courseId: gradeForm.courseId,
            courseName: courseMap[gradeForm.courseId as keyof typeof courseMap] || '',
            semester: gradeForm.semester,
            score: gradeForm.score,
            gradePoint: calculateGradePoint(gradeForm.score),
            examDate: gradeForm.examDate,
            remark: gradeForm.remark,
          };
          gradeList.value[index] = updatedGrade;
          ElMessage.success('更新成功');
        }
      }
      dialogVisible.value = false;
      // 重新初始化图表
      nextTick(() => {
        initCharts();
      });
    } else {
      console.log('验证失败', fields);
    }
  });
};
</script>

<style scoped>
.grades-container {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.chart-container {
  height: 300px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>